<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BeHabit - 习惯养成应用</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .habit-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
        .progress-ring__circle {
            transition: stroke-dashoffset 0.35s;
            transform: rotate(-90deg);
            transform-origin: 50% 50%;
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm">
        <div class="max-w-6xl mx-auto px-4">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <i class="fas fa-seedling text-green-500 text-2xl mr-2"></i>
                    <span class="text-xl font-semibold text-gray-800">BeHabit</span>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="notificationBtn" class="relative p-2 text-gray-500 hover:text-gray-700">
                        <i class="fas fa-bell"></i>
                        <span class="absolute top-0 right-0 h-2 w-2 rounded-full bg-red-500"></span>
                    </button>
                    <div id="userInfo" class="flex items-center cursor-pointer">
                        <div class="h-8 w-8 rounded-full bg-green-100 flex items-center justify-center">
                            <span id="userInitial" class="text-green-600 font-medium"></span>
                        </div>
                        <span id="userEmail" class="text-sm text-gray-600 ml-2"></span>
                    </div>
                    <button onclick="logout()" class="text-gray-600 hover:text-gray-800">
                        <i class="fas fa-sign-out-alt"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-6xl mx-auto px-4 py-8">
        <!-- 欢迎横幅 -->
        <div class="bg-gradient-to-r from-green-400 to-blue-500 rounded-xl p-6 mb-8 text-white">
            <h1 class="text-2xl font-bold mb-2">欢迎回来, 张三!</h1>
            <p class="opacity-90">"微小的改变带来巨大的不同。今天完成你的第一个小习惯吧!"</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 左侧栏 -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 习惯列表 -->
                <div class="bg-white rounded-xl shadow-sm p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-semibold">今日习惯</h2>
                        <button id="addHabitBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center">
                            <i class="fas fa-plus mr-2"></i> 添加习惯
                        </button>
                    </div>
                    
                    <div class="flex border-b border-gray-200 mb-4">
                        <button id="activeHabitsTab" class="py-2 px-4 text-green-600 border-b-2 border-green-500 font-medium">待养成</button>
                        <button id="completedHabitsTab" class="py-2 px-4 text-gray-500 border-b-2 border-transparent font-medium">已彻底完成</button>
                    </div>
                    
                    <div id="habitsContainer" class="space-y-4">
                        <!-- 习惯卡片示例 -->
                        <div class="habit-card bg-white border border-gray-200 rounded-lg p-4 transition-all duration-300">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center space-x-3 habit-info" style="cursor: pointer;">
                                    <div class="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
                                        <i class="fas fa-glass-water text-blue-500"></i>
                                    </div>
                                    <div>
                                        <h3 class="font-medium">喝一杯水</h3>
                                        <p class="text-xs text-gray-500">早上起床后</p>
                                    </div>
                                </div>
                                <button class="habit-complete-btn bg-green-100 text-green-600 px-3 py-1 rounded-full text-sm flex items-center">
                                    <i class="fas fa-check mr-1"></i> 完成
                                </button>
                            </div>
                        </div>
                        
                        <div class="habit-card bg-white border border-gray-200 rounded-lg p-4 transition-all duration-300">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center space-x-3">
                                    <div class="h-10 w-10 rounded-full bg-purple-100 flex items-center justify-center">
                                        <i class="fas fa-book text-purple-500"></i>
                                    </div>
                                    <div>
                                        <h3 class="font-medium">阅读5分钟</h3>
                                        <p class="text-xs text-gray-500">午休时间</p>
                                    </div>
                                </div>
                                <button class="habit-complete-btn bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-sm flex items-center">
                                    标记完成
                                </button>
                            </div>
                        </div>
                        
                        <div class="habit-card bg-white border border-gray-200 rounded-lg p-4 transition-all duration-300">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center space-x-3">
                                    <div class="h-10 w-10 rounded-full bg-yellow-100 flex items-center justify-center">
                                        <i class="fas fa-running text-yellow-500"></i>
                                    </div>
                                    <div>
                                        <h3 class="font-medium">穿上运动鞋</h3>
                                        <p class="text-xs text-gray-500">下班回家时</p>
                                    </div>
                                </div>
                                <button class="habit-complete-btn bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-sm flex items-center">
                                    标记完成
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div id="completedHabitsContainer" class="space-y-4 hidden">
                        <div class="text-center text-gray-500 py-4">
                            <i class="fas fa-spinner fa-spin mr-2"></i> 加载已完成习惯...
                        </div>
                    </div>
                    
                    <!-- 分页控件 -->
                    <div id="paginationControls" class="mt-6 flex items-center justify-between text-sm text-gray-500 hidden">
                        <div>
                            显示 <span id="pageStart">1</span>-<span id="pageEnd">5</span> 条，共 <span id="totalItems">20</span> 条
                        </div>
                        <div class="flex space-x-2">
                            <button id="prevPageBtn" class="bg-gray-100 px-3 py-1 rounded-lg hover:bg-gray-200" disabled>
                                <i class="fas fa-chevron-left"></i>
                            </button>
                            <span class="px-2 py-1">第 <span id="currentPage">1</span> 页</span>
                            <button id="nextPageBtn" class="bg-gray-100 px-3 py-1 rounded-lg hover:bg-gray-200">
                                <i class="fas fa-chevron-right"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 进度统计 -->
                <div class="bg-white rounded-xl shadow-sm p-6">
                    <h2 class="text-xl font-semibold mb-6">习惯进度</h2>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                        <div class="bg-blue-50 rounded-lg p-4 text-center">
                            <p class="text-sm text-blue-600 mb-1">连续天数</p>
                            <p class="text-2xl font-bold text-blue-800">7</p>
                        </div>
                        <div class="bg-green-50 rounded-lg p-4 text-center">
                            <p class="text-sm text-green-600 mb-1">本月完成</p>
                            <p class="text-2xl font-bold text-green-800">21</p>
                        </div>
                        <div class="bg-purple-50 rounded-lg p-4 text-center">
                            <p class="text-sm text-purple-600 mb-1">习惯总数</p>
                            <p class="text-2xl font-bold text-purple-800">5</p>
                        </div>
                        <div class="bg-yellow-50 rounded-lg p-4 text-center">
                            <p class="text-sm text-yellow-600 mb-1">动机分数</p>
                            <p class="text-2xl font-bold text-yellow-800">78</p>
                        </div>
                    </div>
                    <div class="h-64">
                        <canvas id="progressChart"></canvas>
                    </div>
                </div>
            </div>
            
            <!-- 右侧栏 -->
            <div class="space-y-6">
                <!-- 动机评估 -->
                <div class="bg-white rounded-xl shadow-sm p-6">
                    <h2 class="text-xl font-semibold mb-4">动机评估</h2>
                    <div class="mb-4">
                        <div class="flex justify-between mb-1">
                            <span class="text-sm font-medium text-gray-700">当前动机水平</span>
                            <span class="text-sm font-medium text-gray-700">78/100</span>
                        </div>
                        <div class="w-full bg-gray-200 rounded-full h-2.5">
                            <div class="bg-green-500 h-2.5 rounded-full" style="width: 78%"></div>
                        </div>
                    </div>
                    <p class="text-sm text-gray-600 mb-4">你的动机水平良好! 继续保持这些小习惯会更容易。</p>
                    <button class="w-full bg-blue-50 text-blue-600 py-2 rounded-lg text-sm font-medium">
                        重新评估我的动机
                    </button>
                </div>
                
                <!-- 成就徽章 -->
                <div class="bg-white rounded-xl shadow-sm p-6">
                    <h2 class="text-xl font-semibold mb-4">成就徽章</h2>
                    <div class="grid grid-cols-3 gap-3">
                        <div class="flex flex-col items-center">
                            <div class="h-12 w-12 rounded-full bg-yellow-100 flex items-center justify-center mb-1">
                                <i class="fas fa-medal text-yellow-500"></i>
                            </div>
                            <span class="text-xs text-center">3天连胜</span>
                        </div>
                        <div class="flex flex-col items-center">
                            <div class="h-12 w-12 rounded-full bg-blue-100 flex items-center justify-center mb-1">
                                <i class="fas fa-leaf text-blue-500"></i>
                            </div>
                            <span class="text-xs text-center">喝水达人</span>
                        </div>
                        <div class="flex flex-col items-center">
                            <div class="h-12 w-12 rounded-full bg-green-100 flex items-center justify-center mb-1">
                                <i class="fas fa-fire text-green-500"></i>
                            </div>
                            <span class="text-xs text-center">习惯启动</span>
                        </div>
                    </div>
                </div>
                
                <!-- 习惯建议 -->
                <div class="bg-white rounded-xl shadow-sm p-6">
                    <h2 class="text-xl font-semibold mb-4">为你推荐</h2>
                    <div class="space-y-3">
                        <div class="flex items-start space-x-3">
                            <div class="h-8 w-8 rounded-full bg-purple-100 flex-shrink-0 flex items-center justify-center mt-1">
                                <i class="fas fa-book-open text-purple-500 text-xs"></i>
                            </div>
                            <div>
                                <p class="text-sm font-medium">睡前写日记</p>
                                <p class="text-xs text-gray-500">只需写下3件感恩的事</p>
                            </div>
                        </div>
                        <div class="flex items-start space-x-3">
                            <div class="h-8 w-8 rounded-full bg-red-100 flex-shrink-0 flex items-center justify-center mt-1">
                                <i class="fas fa-dumbbell text-red-500 text-xs"></i>
                            </div>
                            <div>
                                <p class="text-sm font-medium">做5个俯卧撑</p>
                                <p class="text-xs text-gray-500">起床后立即完成</p>
                            </div>
                        </div>
                        <div class="flex items-start space-x-3">
                            <div class="h-8 w-8 rounded-full bg-indigo-100 flex-shrink-0 flex items-center justify-center mt-1">
                                <i class="fas fa-mobile-alt text-indigo-500 text-xs"></i>
                            </div>
                            <div>
                                <p class="text-sm font-medium">手机勿扰模式</p>
                                <p class="text-xs text-gray-500">晚餐时间开启1小时</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加习惯模态框 -->
    <div id="addHabitModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-6 w-full max-w-md fade-in modal-content">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">添加新习惯</h3>
                <button id="closeModalBtn" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="addHabitForm" class="space-y-4">
                <div>
                    <label for="habitName" class="block text-sm font-medium text-gray-700 mb-1">习惯名称</label>
                    <input type="text" id="habitName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent" placeholder="例如: 喝一杯水">
                </div>
                
                <div>
                    <label for="habitTrigger" class="block text-sm font-medium text-gray-700 mb-1">触发方式</label>
                    <select id="habitTrigger" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent">
                        <option value="time">时间提醒</option>
                        <option value="location">位置提醒</option>
                        <option value="activity">活动后提醒</option>
                    </select>
                </div>
                
                <div id="timeTriggerSection">
                    <label for="habitTime" class="block text-sm font-medium text-gray-700 mb-1">提醒时间</label>
                    <input type="time" id="habitTime" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent">
                </div>
                
                <div id="locationTriggerSection" class="hidden">
                    <label for="habitLocation" class="block text-sm font-medium text-gray-700 mb-1">位置</label>
                    <input type="text" id="habitLocation" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent" placeholder="例如: 到家时">
                </div>
                
                <div>
                    <label for="habitIcon" class="block text-sm font-medium text-gray-700 mb-1">选择图标</label>
                    <div class="grid grid-cols-5 gap-2">
                        <button type="button" class="icon-btn p-2 border rounded-lg hover:bg-gray-100" data-icon="glass-water">
                            <i class="fas fa-glass-water text-blue-500"></i>
                        </button>
                        <button type="button" class="icon-btn p-2 border rounded-lg hover:bg-gray-100" data-icon="book">
                            <i class="fas fa-book text-purple-500"></i>
                        </button>
                        <button type="button" class="icon-btn p-2 border rounded-lg hover:bg-gray-100" data-icon="running">
                            <i class="fas fa-running text-yellow-500"></i>
                        </button>
                        <button type="button" class="icon-btn p-2 border rounded-lg hover:bg-gray-100" data-icon="meditation">
                            <i class="fas fa-spa text-green-500"></i>
                        </button>
                        <button type="button" class="icon-btn p-2 border rounded-lg hover:bg-gray-100" data-icon="mobile">
                            <i class="fas fa-mobile-alt text-indigo-500"></i>
                        </button>
                    </div>
                    <input type="hidden" id="selectedIcon" value="glass-water">
                </div>
                
                <div class="pt-2">
                    <button type="submit" class="w-full bg-green-500 hover:bg-green-600 text-white py-2 rounded-lg font-medium">
                        添加习惯
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 完成习惯确认弹窗 -->
    <div id="completeHabitModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl p-6 w-full max-w-sm fade-in modal-content">
            <div class="text-center">
                <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 mb-4">
                    <i class="fas fa-check text-green-600"></i>
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-2" id="completedHabitName">喝一杯水</h3>
                <p class="text-sm text-gray-500 mb-6">恭喜你完成了这个习惯!</p>
                <div class="flex space-x-3">
                    <button id="cancelCompleteBtn" type="button" class="flex-1 bg-gray-100 text-gray-700 py-2 rounded-lg text-sm font-medium">
                        取消
                    </button>
                    <button id="confirmCompleteBtn" type="button" class="flex-1 bg-green-500 text-white py-2 rounded-lg text-sm font-medium">
                        确认完成
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 认证表单 -->
    <div id="authForm" class="fixed inset-0 flex items-center justify-center z-50">
        <div class="bg-white p-8 rounded-lg shadow-md w-96 modal-content">
            <h1 class="text-2xl font-bold text-center mb-6">BeHabit</h1>
            <div class="space-y-4">
                <input type="email" id="email" placeholder="邮箱" class="w-full px-4 py-2 border rounded-lg">
                <input type="password" id="password" placeholder="密码" class="w-full px-4 py-2 border rounded-lg">
                <div id="verificationCodeContainer" class="hidden">
                    <div class="flex space-x-2">
                        <input type="text" id="verificationCode" placeholder="验证码" class="w-full px-4 py-2 border rounded-lg">
                        <button type="button" id="getCodeBtn" class="bg-blue-500 text-white px-4 py-2 rounded-lg">获取验证码</button>
                    </div>
                </div>
                <button onclick="login()" class="w-full bg-blue-500 text-white py-2 rounded-lg">登录</button>
                <button onclick="register()" class="w-full bg-gray-200 text-gray-700 py-2 rounded-lg">注册</button>
                <div class="text-center">
                    <a href="#" id="toggleRegisterBtn" class="text-blue-500 text-sm">切换到注册</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        document.addEventListener('DOMContentLoaded', function() {
            // 检查是否已登录
            const token = localStorage.getItem('token');
            const userEmail = localStorage.getItem('userEmail');
            
            if (token && userEmail) {
                // 已登录，隐藏登录表单，显示主页面
                document.getElementById('authForm').classList.add('hidden');
                document.getElementById('mainApp').classList.remove('hidden');
                
                // 显示用户信息
                document.getElementById('userInitial').textContent = userEmail.charAt(0).toUpperCase();
                document.getElementById('userEmail').textContent = userEmail;
            } else {
                // 未登录，显示登录表单
                document.getElementById('authForm').classList.remove('hidden');
                document.getElementById('mainApp').classList.add('hidden');
                
                // 初始化登录/注册切换功能
                const toggleRegisterBtn = document.getElementById('toggleRegisterBtn');
                const verificationCodeContainer = document.getElementById('verificationCodeContainer');
                const loginBtn = document.querySelector('button[onclick="login()"]');
                const registerBtn = document.querySelector('button[onclick="register()"]');
                
                let isLoginMode = true;
                
                toggleRegisterBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    isLoginMode = !isLoginMode;
                    
                    if (isLoginMode) {
                        toggleRegisterBtn.textContent = '切换到注册';
                        verificationCodeContainer.classList.add('hidden');
                        loginBtn.classList.remove('hidden');
                        registerBtn.classList.add('hidden');
                    } else {
                        toggleRegisterBtn.textContent = '切换到登录';
                        verificationCodeContainer.classList.remove('hidden');
                        loginBtn.classList.add('hidden');
                        registerBtn.classList.remove('hidden');
                    }
                });
                
                // 初始状态
                verificationCodeContainer.classList.add('hidden');
                registerBtn.classList.add('hidden');
                
                // 获取验证码按钮
                const getCodeBtn = document.getElementById('getCodeBtn');
                getCodeBtn.addEventListener('click', function() {
                    const email = document.getElementById('email').value;
                    if (!email) {
                        alert('请先输入邮箱地址');
                        return;
                    }
                    
                    // 禁用按钮，开始倒计时
                    getCodeBtn.disabled = true;
                    let countdown = 60;
                    getCodeBtn.textContent = `${countdown}秒后重试`;
                    
                    const timer = setInterval(() => {
                        countdown--;
                        getCodeBtn.textContent = `${countdown}秒后重试`;
                        if (countdown <= 0) {
                            clearInterval(timer);
                            getCodeBtn.disabled = false;
                            getCodeBtn.textContent = '获取验证码';
                        }
                    }, 1000);
                    
                    // 发送获取验证码请求
                    fetch(`/api/auth/verification-code?email=${email}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                alert(data.error);
                            } else {
                                alert('验证码已发送，请查收');
                            }
                        })
                        .catch(error => {
                            console.error('获取验证码错误:', error);
                            alert('获取验证码失败，请稍后重试');
                        });
                });
            }
            
            // 进度图表
            const ctx = document.getElementById('progressChart').getContext('2d');
            const progressChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                    datasets: [
                        {
                            label: '习惯完成率',
                            data: [30, 45, 60, 65, 75, 85],
                            borderColor: '#10B981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            tension: 0.3,
                            fill: true
                        },
                        {
                            label: '动机分数',
                            data: [50, 55, 65, 70, 75, 78],
                            borderColor: '#3B82F6',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            tension: 0.3,
                            fill: true
                        }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });

            // 用户菜单切换
            const userMenuBtn = document.getElementById('userMenuBtn');
            const userMenu = document.getElementById('userMenu');
            
            userMenuBtn.addEventListener('click', function() {
                userMenu.classList.toggle('hidden');
            });

            // 点击其他地方关闭菜单
            document.addEventListener('click', function(e) {
                if (!userMenuBtn.contains(e.target) && !userMenu.contains(e.target)) {
                    userMenu.classList.add('hidden');
                }
            });

            // 添加习惯模态框
            const addHabitBtn = document.getElementById('addHabitBtn');
            const addHabitModal = document.getElementById('addHabitModal');
            const closeModalBtn = document.getElementById('closeModalBtn');
            
            addHabitBtn.addEventListener('click', function() {
                addHabitModal.classList.remove('hidden');
            });
            
            closeModalBtn.addEventListener('click', function() {
                addHabitModal.classList.add('hidden');
            });
            
            // 点击模态框外部关闭模态框
            addHabitModal.addEventListener('click', function(e) {
                // 如果点击的是模态框的背景部分（不是内容部分）
                if (!e.target.closest('.modal-content') && e.target === this) {
                    addHabitModal.classList.add('hidden');
                }
            });
            
            // 完成习惯弹窗点击外部关闭
            const completeHabitModal = document.getElementById('completeHabitModal');
            completeHabitModal.addEventListener('click', function(e) {
                if (!e.target.closest('.modal-content') && e.target === this) {
                    completeHabitModal.classList.add('hidden');
                }
            });

            // 切换习惯列表的tab
            const activeHabitsTab = document.getElementById('activeHabitsTab');
            const completedHabitsTab = document.getElementById('completedHabitsTab');
            const habitsContainer = document.getElementById('habitsContainer');
            const completedHabitsContainer = document.getElementById('completedHabitsContainer');
            
            // 注意：tab点击事件的处理逻辑已移至app.js文件中

            // 触发方式切换
            const habitTrigger = document.getElementById('habitTrigger');
            const timeTriggerSection = document.getElementById('timeTriggerSection');
            const locationTriggerSection = document.getElementById('locationTriggerSection');
            
            habitTrigger.addEventListener('change', function() {
                if (this.value === 'time') {
                    timeTriggerSection.classList.remove('hidden');
                    locationTriggerSection.classList.add('hidden');
                } else if (this.value === 'location') {
                    timeTriggerSection.classList.add('hidden');
                    locationTriggerSection.classList.remove('hidden');
                } else {
                    timeTriggerSection.classList.add('hidden');
                    locationTriggerSection.classList.add('hidden');
                }
            });

            // 图标选择
            const iconButtons = document.querySelectorAll('.icon-btn');
            const selectedIcon = document.getElementById('selectedIcon');
            
            iconButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 移除所有按钮的选中状态
                    iconButtons.forEach(btn => {
                        btn.classList.remove('bg-blue-50', 'border-blue-300');
                    });
                    
                    // 添加当前按钮的选中状态
                    this.classList.add('bg-blue-50', 'border-blue-300');
                    
                    // 更新选中的图标值
                    selectedIcon.value = this.dataset.icon;
                });
            });

            // 习惯完成交互
            const habitCompleteBtns = document.querySelectorAll('.habit-complete-btn');
            const completedHabitName = document.getElementById('completedHabitName');
            const confirmCompleteBtn = document.getElementById('confirmCompleteBtn');
            const cancelCompleteBtn = document.getElementById('cancelCompleteBtn');
            
            let currentHabitCard = null;
            
            habitCompleteBtns.forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.stopPropagation(); // 阻止事件冒泡
                    currentHabitCard = this.closest('.habit-card');
                    const habitName = currentHabitCard.querySelector('h3').textContent;
                    completedHabitName.textContent = habitName;
                    completeHabitModal.classList.remove('hidden');
                });
            });
            
            // 习惯卡片点击查看详情
            const habitInfos = document.querySelectorAll('.habit-info');
            habitInfos.forEach(info => {
                info.addEventListener('click', function() {
                    const habitCard = this.closest('.habit-card');
                    const habitName = habitCard.querySelector('h3').textContent;
                    alert(`查看${habitName}的完成情况`);
                    // 这里添加查看习惯详情的功能
                });
            });
            
            confirmCompleteBtn.addEventListener('click', function() {
                if (currentHabitCard) {
                    const btn = currentHabitCard.querySelector('.habit-complete-btn');
                    btn.innerHTML = '<i class="fas fa-check mr-1"></i> 完成';
                    btn.classList.remove('bg-gray-100', 'text-gray-600');
                    btn.classList.add('bg-green-100', 'text-green-600');
                    
                    // 添加动画效果
                    currentHabitCard.classList.add('bg-green-50');
                    setTimeout(() => {
                        currentHabitCard.classList.remove('bg-green-50');
                    }, 1000);
                }
                
                completeHabitModal.classList.add('hidden');
            });
            
            cancelCompleteBtn.addEventListener('click', function() {
                completeHabitModal.classList.add('hidden');
            });

            // 表单提交
            const addHabitForm = document.getElementById('addHabitForm');
            
            addHabitForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const habitName = document.getElementById('habitName').value;
                const habitTrigger = document.getElementById('habitTrigger').value;
                const habitIcon = document.getElementById('selectedIcon').value;
                
                // 创建新的习惯卡片
                const habitsContainer = document.getElementById('habitsContainer');
                const newHabitCard = document.createElement('div');
                newHabitCard.className = 'habit-card bg-white border border-gray-200 rounded-lg p-4 transition-all duration-300';
                
                let triggerText = '';
                if (habitTrigger === 'time') {
                    const time = document.getElementById('habitTime').value;
                    triggerText = `每天 ${time}`;
                } else if (habitTrigger === 'location') {
                    const location = document.getElementById('habitLocation').value;
                    triggerText = location;
                } else {
                    triggerText = '活动后提醒';
                }
                
                // 获取图标对应的颜色
                let iconColor = 'blue';
                const iconColorMap = {
                    'glass-water': 'blue',
                    'book': 'purple',
                    'running': 'yellow',
                    'meditation': 'green',
                    'mobile': 'indigo'
                };
                
                if (iconColorMap[habitIcon]) {
                    iconColor = iconColorMap[habitIcon];
                }
                
                newHabitCard.innerHTML = `
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-3">
                            <div class="h-10 w-10 rounded-full bg-${iconColor}-100 flex items-center justify-center">
                                <i class="fas fa-${habitIcon} text-${iconColor}-500"></i>
                            </div>
                            <div>
                                <h3 class="font-medium">${habitName}</h3>
                                <p class="text-xs text-gray-500">${triggerText}</p>
                            </div>
                        </div>
                        <button class="habit-complete-btn bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-sm flex items-center">
                            标记完成
                        </button>
                    </div>
                `;
                
                // 添加到容器顶部
                habitsContainer.prepend(newHabitCard);
                
                // 为新按钮添加事件监听
                newHabitCard.querySelector('.habit-complete-btn').addEventListener('click', function() {
                    currentHabitCard = this.closest('.habit-card');
                    completedHabitName.textContent = currentHabitCard.querySelector('h3').textContent;
                    completeHabitModal.classList.remove('hidden');
                });
                
                // 重置表单并关闭模态框
                addHabitForm.reset();
                addHabitModal.classList.add('hidden');
                
                // 显示成功提示
                alert('习惯添加成功!');
            });

            // 认证相关函数
            const authSwitchBtn = document.getElementById('authSwitchBtn');
            const authSubmitBtn = document.getElementById('authSubmitBtn');
            const verificationCodeContainer = document.getElementById('verificationCodeContainer');
            const getCodeBtn = document.getElementById('getCodeBtn');
            
            let isLoginMode = true;
            
            authSwitchBtn.addEventListener('click', function() {
                isLoginMode = !isLoginMode;
                if (isLoginMode) {
                    authSwitchBtn.textContent = '创建账号';
                    authSubmitBtn.textContent = '登录';
                    verificationCodeContainer.classList.add('hidden');
                } else {
                    authSwitchBtn.textContent = '返回登录';
                    authSubmitBtn.textContent = '注册';
                    verificationCodeContainer.classList.remove('hidden');
                }
            });
            
            // 验证码获取
            getCodeBtn.addEventListener('click', function() {
                const email = document.getElementById('email').value;
                if (!email) {
                    alert('请先输入邮箱地址');
                    return;
                }
                
                // 禁用按钮，开始倒计时
                getCodeBtn.disabled = true;
                let countdown = 60;
                getCodeBtn.textContent = `${countdown}秒后重试`;
                
                const timer = setInterval(() => {
                    countdown--;
                    getCodeBtn.textContent = `${countdown}秒后重试`;
                    if (countdown <= 0) {
                        clearInterval(timer);
                        getCodeBtn.disabled = false;
                        getCodeBtn.textContent = '获取验证码';
                    }
                }, 1000);
                
                // 发送获取验证码请求
                fetch(`/api/auth/verification-code?email=${email}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.error) {
                            alert(data.error);
                        } else {
                            alert('验证码已发送，请查收');
                        }
                    })
                    .catch(error => {
                        console.error('获取验证码错误:', error);
                        alert('获取验证码失败，请稍后重试');
                    });
            });
            
            // 登录/注册提交
            authSubmitBtn.addEventListener('click', function() {
                if (isLoginMode) {
                    login();
                } else {
                    register();
                }
            });

            // 为所有模态框添加点击外部关闭功能
            const modalIds = [
                'habitDetailsModal',
                'articleDetailModal',
                'allArticlesModal',
                'addHabitModal',  // 添加
                'completeHabitModal',  // 添加
                'authForm'  // 添加
            ];
            
            // 为每个模态框添加点击外部关闭事件
            modalIds.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.addEventListener('click', function(e) {
                        // 如果点击的是模态框背景而不是内容
                        if (!e.target.closest('.modal-content') && e.target === this) {
                            // 根据不同模态框调用相应的关闭函数
                            if (modalId === 'habitDetailsModal') {
                                hideHabitDetailsModal();
                            } else if (modalId === 'articleDetailModal') {
                                hideArticleDetailModal();
                            } else if (modalId === 'allArticlesModal') {
                                hideAllArticlesModal();
                            } else if (modalId === 'addHabitModal') {
                                addHabitModal.classList.add('hidden');
                            } else if (modalId === 'completeHabitModal') {
                                completeHabitModal.classList.add('hidden');
                            }
                            // authForm不需要关闭功能
                        }
                    });
                }
            });
        });
        
        // 登录函数
        function login() {
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            
            if (!email || !password) {
                alert('请填写电子邮箱和密码');
                return;
            }
            
            fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email, password })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    // 保存token和邮箱
                    localStorage.setItem('token', data.token);
                    localStorage.setItem('userEmail', email);
                    
                    // 刷新页面
                    window.location.reload();
                }
            })
            .catch(error => {
                console.error('登录错误:', error);
                alert('登录失败，请稍后重试');
            });
        }

        // 注册函数
        function register() {
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            const verificationCode = document.getElementById('verificationCode').value;
            
            if (!email || !password || !verificationCode) {
                alert('请填写所有字段');
                return;
            }
            
            fetch('/api/auth/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email, password, verificationCode })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    // 保存token和邮箱
                    localStorage.setItem('token', data.token);
                    localStorage.setItem('userEmail', email);
                    
                    // 刷新页面
                    window.location.reload();
                }
            })
            .catch(error => {
                console.error('注册错误:', error);
                alert('注册失败，请稍后重试');
            });
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('userEmail');
            window.location.reload();
        }
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=zhebie/behabit" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>